$(document).ready(function() {
	SB.HomeView = Backbone.View.extend({
		el : "#body",

		initialize : function() {
			_.bindAll(this, 'render', 'closeView', 'newBill', 'sentBills', 'receivedBills');
			SB.router.on('route:newBill', this.newBill);
			SB.router.on('route:sentBills', this.sentBills);
			SB.router.on('route:receivedBills', this.receivedBills);
		},

		render : function() {
			return this;
		},

		closeView : function() {
			VM.closeView('newBillView');
			VM.closeView('createdBillsView');
		},

		resetMenu : function() {
			this.$('li').removeClass('active');
			this.$('li a i').removeClass('icon-white');
			window.scrollTo(0,0);
		},

		newBill : function() {
			this.closeView();
			this.resetMenu();
			this.$('#new').addClass('active');
			this.$('#new a i').addClass('icon-white');

			var newBillView = VM.createView('newBillView', function() {
				return new SB.NewBillView();
			});
			this.$('#detail').html(newBillView.render().el);
			$('textarea').autosize();
			
		},

		sentBills : function() {
			this.closeView();
			this.resetMenu();
			this.$('#sent').addClass('active');
			this.$('#sent a i').addClass('icon-white');

			SB.billViews = VM.createView("billViews", function(){
				return new SB.BillCollectionView();
			});
			if (SB.billCollection.length == 0) {
				SB.billCollection.reset(SB.createdBills);
			}
			console.log("sent bill");
			this.$('#detail').html(SB.billViews.render().el);
		},

		receivedBills : function() {
			this.closeView();
			this.resetMenu();
			this.$('#received').addClass('active');
			this.$('#received a i').addClass('icon-white');
			
			SB.receivedBillViews = VM.createView("billViews", function(){
				return new SB.ReceivedBillCollectionView();
			});
			if (SB.receivedBillCollection.length == 0) {
				SB.receivedBillCollection.reset(SB.requestedBills);
			}
			this.$('#detail').html(SB.receivedBillViews.render().el);
		}
	});

	// Initialize and render
	// Initialize global instance, it is accessible to all functions

	SB.homeView = new SB.HomeView();
	SB.homeView.render();
	
	// Set username
	var currentUser = SB.user.name;
	if (!currentUser) {
		currentUser = SB.user.auth_ids[0];
	}
	
	SB.homeView.$('#current-user').html(currentUser);

	Backbone.history.start();
});
